let mysql = require("mysql");
let fs = require("fs");
let http = require("http");

function query(sql, values) {
    return new Promise(function (resolve, reject) {
        let db = mysql.createConnection({
            host: 'localhost',
            user: 'root',
            password: 'root',
            port: '3306',
            database: 'data'
        })
        db.connect();

        db.query(sql, values, function (err, result) {
            if (err) {
                console.log(reject(err));
            } else {
                console.log(resolve(result));
            }
        })
        db.end();
    })
}
//查询数据
let sql = 'SELECT * FROM china';
//values为占位符
let values = ["龙岩", 0, "2020年3月10号"];
let html = '';

async function select(sql, values) {
    let result = await query(sql, values)
    for (let row in result) {
        html += '<tr>'
        html += '<td>' + result[row].city + '</td>'
        html += '<td>' + result[row].nums + '</td>'
        html += '<td>' + result[row].date + '</td>'
        html += '</tr>'
    }
}
select(sql, values);

let serve = http.createServer(function (req, res) {
    if (req.url == '/' || req.url == '/index.html') {
        let bf = fs.readFileSync('./index.html')
        let outPutStr = bf.toString();
        let str = outPutStr.replace('{{result}}', html);
        res.write(str);
        res.end();
    } else {
        res.end('404')
    }
})

serve.listen(3000,function () {
    console.log("服务已启动 http://127.0.0.1:3000");
})